import type { AxiosInstance, AxiosRequestConfig } from "axios";
import axios from "axios";
import { ResultEnum } from "@/enums/httpEnum";
import type { ResultData } from "@/api/interface";
import { setupInterceptors } from "@/api/helper/interceptors";

const config: AxiosRequestConfig = {
  baseURL: import.meta.env.VITE_API_URL as string, // 后端接口地址
  timeout: ResultEnum.TIMEOUT as number, // 请求超时时间
  withCredentials: true, // 跨域时候允许携带凭证
};

class RequestHttp {
  service: AxiosInstance;
  public constructor(config: AxiosRequestConfig) {
    // instantiation
    this.service = axios.create(config);
  }
  /**
   * @description 常用请求方法封装
   */
  get<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.get(url, { params, ..._object });
  }
  post<T>(url: string, params?: object | string, _object = {}): Promise<ResultData<T>> {
    return this.service.post(url, params, _object);
  }
  put<T>(url: string, params?: object, _object = {}): Promise<ResultData<T>> {
    return this.service.put(url, params, _object);
  }
  delete<T>(url: string, params?: any, _object = {}): Promise<ResultData<T>> {
    return this.service.delete(url, { params, ..._object });
  }
  download(url: string, params?: object, _object = {}): Promise<BlobPart> {
    return this.service.post(url, params, { ..._object, responseType: "blob" });
  }
}

const requestHttp = new RequestHttp(config);
setupInterceptors(requestHttp.service);

export default requestHttp;
